package com.hzf.wxplatform.common.utils;

import com.alibaba.fastjson.util.Base64;
import com.google.gson.Gson;
import com.hzf.common.face.faceModel.FaceEntity;
import com.hzf.common.gps.BaiduGPS;
import com.hzf.common.util.*;
import com.hzf.common.wxgps.WxGps;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * describe: TODO
 * creat_user: 白开水
 * creat_time: 2017/11/24   21:09
 **/
public class WxGetGpsUtils {
    public static Logger log = Logger.getLogger(WxGetGpsUtils.class);

    public static Map processRequest(HttpServletRequest request,String latitude,String longitude,String accuracy) {
        WxGps wxGps = new WxGps();
        wxGps.setLatitude(latitude);
        wxGps.setLongitude(longitude);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("from","2");
        params.put("to", "4");
        params.put("x", wxGps.getLatitude());
        params.put("y", wxGps.getLongitude());
        String result = HttpUtil.doGet("http://api.map.baidu.com/ag/coord/convert",params);
        JSONObject  jsonObject = JSONObject.fromObject(result);
        byte[] xbuff = Base64.decodeFast((String) jsonObject.get("x"));
        byte[] ybuff = Base64.decodeFast((String) jsonObject.get("y"));
        result = new String(xbuff) + "|" + new String(ybuff);
        Map<String,Object> addressMap = new HashMap<String,Object>();
        addressMap.put("location",new String(xbuff)+","+new String(ybuff));
        addressMap.put("ak","FGKbnR45Ly94F6mXVGEkNPOTCjN9m0sg");
        addressMap.put("output","json");
        String    result1=HttpUtil.doGet("http://api.map.baidu.com/geocoder/v2/",addressMap);
        BaiduGps baiduGPS =parseJsonWithGson(result1,BaiduGps.class);
        String address = baiduGPS.getResult().getFormatted_address()+baiduGPS.getResult().getSematic_description();
        String adcode = baiduGPS.getResult().getAddressComponent().getAdcode().substring(0,baiduGPS.getResult().getAddressComponent().getAdcode().length()-2);
        Double lat = baiduGPS.getResult().getLocation().getLat();
        Double lng = baiduGPS.getResult().getLocation().getLng();
        Map <String,String>map = new HashMap();


        if(null!=adcode){
            System.out.println(adcode);
            map.put("address",address);
            map.put("adcode",adcode);
            map.put("lat",lat.toString());
            map.put("lng",lng.toString());

            return map;
        }
        System.out.println(adcode);
        return map;

    }

    public static Map processAddreess(HttpServletRequest request,String latitude,String longitude,String accuracy) {
        System.out.println(latitude+longitude);
        Map<String,Object> addressMap = new HashMap<String,Object>();
        addressMap.put("location",longitude+","+latitude);
        addressMap.put("ak","FGKbnR45Ly94F6mXVGEkNPOTCjN9m0sg");
        addressMap.put("output","json");
        String    result1=HttpUtil.doGet("http://api.map.baidu.com/geocoder/v2/",addressMap);
        BaiduGps baiduGPS =parseJsonWithGson(result1,BaiduGps.class);
        String address = baiduGPS.getResult().getFormatted_address()+baiduGPS.getResult().getSematic_description();
        String adcode = baiduGPS.getResult().getAddressComponent().getAdcode().substring(0,baiduGPS.getResult().getAddressComponent().getAdcode().length()-2);
        Double lat = baiduGPS.getResult().getLocation().getLat();
        Double lng = baiduGPS.getResult().getLocation().getLng();
        Map <String,String>map = new HashMap();


        if(null!=adcode){
            System.out.println(adcode);
            map.put("address",address);
            map.put("adcode",adcode);
            map.put("lat",lat.toString());
            map.put("lng",lng.toString());

            return map;
        }
        System.out.println(adcode);
        return map;

    }

    public static String lngRequest(HttpServletRequest request,String latitude,String longitude) {
        WxGps wxGps = new WxGps();
        wxGps.setLatitude(latitude);
        wxGps.setLongitude(longitude);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("from","2");
        params.put("to", "4");
        params.put("x", wxGps.getLongitude());
        params.put("y", wxGps.getLatitude());


        String result = HttpUtil.doGet("http://api.map.baidu.com/ag/coord/convert",params);
        return result;

    }
    private Object json2Object(JSONObject json,Class pojo) throws Exception{
        // 首先得到pojo所定义的字段
        Field[] fields = pojo.getDeclaredFields();
        // 根据传入的Class动态生成pojo对象
        Object obj = pojo.newInstance();
        for(Field field: fields){
            // 设置字段可访问（必须，否则报错）
            field.setAccessible(true);
            // 得到字段的属性名
            String name = field.getName();
            // 这一段的作用是如果字段在JSONObject中不存在会抛出异常，如果出异常，则跳过。
            try{
                json.get(name);
            }catch(Exception ex){
                continue;
            }
            if(json.get(name) != null && !"".equals(json.getString(name))){
                // 根据字段的类型将值转化为相应的类型，并设置到生成的对象中。
                if(field.getType().equals(Long.class) || field.getType().equals(long.class)){
                    field.set(obj, Long.parseLong(json.getString(name)));
                }else if(field.getType().equals(String.class)){
                    field.set(obj, json.getString(name));
                } else if(field.getType().equals(Double.class) || field.getType().equals(double.class)){
                    field.set(obj, Double.parseDouble(json.getString(name)));
                } else if(field.getType().equals(Integer.class) || field.getType().equals(int.class)){
                    field.set(obj, Integer.parseInt(json.getString(name)));
                } else{
                    continue;
                }
            }
        }
        return obj;
    }
    // 将Json数据解析成相应的映射对象
   public static <T> T parseJsonWithGson(String jsonData, Class<T> type) {
       System.out.println(jsonData);
             Gson gson = new Gson();
             T result = gson.fromJson(jsonData, type);
             return result;
           }
    /**
     * 从Request对象中获得客户端IP，处理了HTTP代理服务器和Nginx的反向代理截取了ip
     * @param request
     * @return ip
     */
    public static String getLocalIp(HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        String forwarded = request.getHeader("X-Forwarded-For");
        String realIp = request.getHeader("X-Real-IP");

        String ip = null;
        if (realIp == null) {
            if (forwarded == null) {
                ip = remoteAddr;
            } else {
                ip = remoteAddr;
            }
        } else {
            if (realIp.equals(forwarded)) {
                ip = realIp;
            } else {
                if(forwarded != null){
                    forwarded = forwarded.split(",")[0];
                }
                ip = realIp;
            }
        }
        return ip;
    }
}
